package com.agmte.api.config;

import com.agmte.api.component.response.CustomApiResult;
import com.agmte.api.component.response.ResultCode;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class ApiGlobalExceptionBe59750b {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public CustomApiResult<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return CustomApiResult.error(ResultCode.FAILED, "参数有误", errors);
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CustomApiResult<?> handleException(Exception ex) {
        ex.printStackTrace();
        return CustomApiResult.error(ResultCode.FAILED, ex.getMessage());
    }
}